import {getUserInfo, login} from "@/api/sys";
import md5 from "md5";
import {getItem, removeAllItem, setItem} from "@/utils/storage";
import router from "@/router";
import {setTimeStamp} from "@/utils/auth";

export default ({
  namespaced: true,
  state: () => ({
    token: getItem('token') || '',
    userInfo: {}
  }),
  mutations: {
    setToken(state, token) {
      state.token = token
      setItem('token', token)
    },
    setUserInfo(state, userInfo) {
      state.userInfo = userInfo
    }
  },
  actions: {
    // 登录
    onLogin(context, userInfo) {
      const {username, password} = userInfo
      return new Promise((resolve) => {
        login({
          username,
          password: md5(password)
        }).then(res => {
          this.commit('user/setToken', res.token)
          setTimeStamp()
          router.push('/')
          resolve()
        })
      })
    },
    // 获取用户信息
    async getUserInfo(context, userInfo) {
      const res = await getUserInfo()
      this.commit('user/setUserInfo', res)
      return res
    },
    // 退出登录
    logout() {
      this.commit('user/setToken', '')
      this.commit('user/setUserInfo', {})
      removeAllItem()
      router.push('/login')
    }
  }
})
